//
//  MDDeviceViewController.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 5/18/15.
//  Copyright (c) 2015 Minus. All rights reserved.
//

#import "MDDeviceViewController.h"
#import "MDXPGApplianceApi.h"
#import "QrCodeViewController.h"
#import "DownPicker.h"

@interface MDDeviceViewController ()
{
    NSString *_homeSSID;
    NSString *_deviceSSID;
    NSString *_qrcodeSN;
    
    NSMutableArray *_wifiList;
    DownPicker *_picker;
    
    MDXPGApplianceApi *_applianceApi;
}

@property (weak, nonatomic) IBOutlet UITextField *textFieldQRCode;
@property (weak, nonatomic) IBOutlet UITextField *textFieldWifiSSID;
@property (weak, nonatomic) IBOutlet UITextField *textFieldWifiPwd;
@property (weak, nonatomic) IBOutlet UILabel *labelDeviceSSID;
@property (weak, nonatomic) IBOutlet UILabel *labelResult;

@end

@implementation MDDeviceViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 获取 MDXPGApplianceApi 实例
    _applianceApi = [MDXPGApplianceApi getInstance];
    
    // 获取当前连接的家庭WIFI名称k
    _homeSSID = [_applianceApi getCurrentSSID];
    
    if (_homeSSID)
    {
        self.textFieldWifiSSID.text = _homeSSID;
    }
    else
    {
        self.textFieldWifiSSID.text = @"Device";
    }
    
    /**
     *  由于没有二维码，这里写死了二维码扫描的结果
     *  真实操作步骤，请参照 actionScanQRCode:
     */
    {
        NSString *scanResult = @"http://www.midea.com/kt_APP/index.html?cd=DC0123456789ABCDEFW021";
        // 先判断二维码是否有效
        if (![[MDXPGApplianceApi getInstance] isQRCodeValid:scanResult])
        {
            self.labelResult.text = @"错误：非美的设备的二维码！";
            return;
        }
        else
        {
            self.labelResult.text = @"扫描二维码成功！";
        }
        
        // 从二维码获取目标设备SN，绑定设备的时候需要用到
        _qrcodeSN = [_applianceApi getSNfromQRCode:scanResult];
        self.textFieldQRCode.text = _qrcodeSN;
        
        // 从二维码获取目标设备的SSID
        _deviceSSID = [_applianceApi getSSIDfromQRCode:scanResult];
        self.labelDeviceSSID.text = _deviceSSID;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


- (IBAction)actionScanQRCode:(id)sender
{
    [self clearResult];
    
    QrCodeViewController *viewController = [[QrCodeViewController alloc] init];
    [self presentViewController:viewController animated:YES completion:nil];
    
    // 扫描二维码返回结果
    [viewController scanQRCode:^(NSString *result) {
        
        // 先判断二维码是否有效
        if (![[MDXPGApplianceApi getInstance] isQRCodeValid:result])
        {
            self.labelResult.text = @"错误：非美的设备的二维码！";
            return;
        }
        else
        {
            self.labelResult.text = @"扫描二维码成功！";
        }
        
        // 从二维码获取目标设备SN，绑定设备的时候需要用到
        _qrcodeSN = [_applianceApi getSNfromQRCode:result];
        self.textFieldQRCode.text = _qrcodeSN;
        
        // 从二维码获取目标设备的SSID，需手动到“设置”页面连接到该SSID
        _deviceSSID = [_applianceApi getSSIDfromQRCode:result];
        self.labelDeviceSSID.text = _deviceSSID;
        NSLog(@"二维码: %@", result);
    }];
}

- (IBAction)actionSearchWifi:(id)sender
{
    // 搜索家庭的wifi前，需要先判断设备是否已进入配置模式
    if (![_applianceApi isDeviceReady])
    {
        self.labelResult.text = [NSString stringWithFormat:@"无法启动搜索，请确认设备是否已上电，且手机wifi是否连到%@", _deviceSSID];
        return;
    }
    
    // 1. 先连接设备
    self.labelResult.text = @"正在连接设备...";
    
    [_applianceApi connectDevice:_deviceSSID completion:^(NSDictionary *dic, NSError *error) {
        
        if (!error) // 连接成功
        {
            // 2. 发送指令让设备进行AP搜索
            self.labelResult.text = @"设备连接成功，正在搜索附近的热点...";
            
            [_applianceApi findWifiApList:^(NSArray *wifiApList, NSError *error) {
                
                if (!error)
                {
                    self.labelResult.text = [NSString stringWithFormat:@"搜索完毕！wifi列表：%@", wifiApList];
                    NSLog(@"wifi list: %@", wifiApList);
                    
                    if ([wifiApList count] > 0)
                    {
                        // 把数据填充到picker
                        if (!_wifiList)
                        {
                            _wifiList = [[NSMutableArray alloc] initWithArray:wifiApList];
                        }
                        else
                        {
                            [_wifiList removeAllObjects];
                            [_wifiList addObjectsFromArray:wifiApList];
                        }
                        
                        // 获取家庭wifi ssid
                        NSMutableArray *pickerSource = [NSMutableArray new];
                        for (NSDictionary *wifiItem in wifiApList)
                        {
                            [pickerSource addObject:wifiItem[@"ssid"]];
                            
                            if ([wifiItem[@"ssid"] isEqualToString:_homeSSID])
                            {
                                _textFieldWifiSSID.text = _homeSSID;
                            }
                        }
                        
                        if (!_picker)
                        {
                            _picker = [[DownPicker alloc] initWithTextField:_textFieldWifiSSID withData:pickerSource];
                        }
                        else
                        {
                            [_picker setData:pickerSource];
                        }
                    }
                }
                else
                {
                    self.labelResult.text = [NSString stringWithFormat:@"搜索热点失败:%@",error.description];
                }
            }];
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"连接设备失败:%@",error.description];
        }
    }];
}

- (IBAction)actionStartBind:(id)sender
{
    [self.view endEditing:YES];
    
    if (![_applianceApi isDeviceReady])
    {
        self.labelResult.text = [NSString stringWithFormat:@"无法启动绑定，请确认设备是否已上电，且手机wifi是否连到%@", _deviceSSID];
        return;
    }
    
    // 根据用户选中的热点设置目标homeSSID
    _homeSSID = _textFieldWifiSSID.text;
    
    // 获取 WIFI 加密类型，默认为 WPA
    MDWifiSecurity security = MDWifiSecurityWPA;
    
    if (_wifiList)
    {
        for (NSDictionary *wifiItem in _wifiList)
        {
            if ([wifiItem[@"ssid"] isEqualToString:_homeSSID])
            {
                security = [wifiItem[@"miType"] integerValue];
            }
        }
    }
    
    // 检查密码长度是否合法
    NSString *password = _textFieldWifiPwd.text;
    
    if (![_applianceApi isValidWifiPassword:password security:security])
    {
        self.labelResult.text = @"密码长度/格式不正确";
        return;
    }
    
    // 绑定设备
    self.labelResult.text = @"正在绑定设备,请耐心等候...";
    
    NSString *deviceName = [@"AC" stringByAppendingString:[_qrcodeSN substringFromIndex:(_qrcodeSN.length-4)]];
    
    [_applianceApi bindDevice:_homeSSID
                     password:password
                     security:security
                     qrcodeSN:_qrcodeSN
                   deviceName:deviceName completion:^(NSDictionary *dic, NSError *error) {
        
        if (!error)
        {
           NSLog(@"result: %@", dic);
           
           if (dic[@"result"] && dic[@"result"][@"id"])// && dic[@"result"][@"model"])
           {
               self.labelResult.text = [NSString stringWithFormat:@"绑定成功，设备ID为:%@", dic[@"result"][@"virtualId"]/*, dic[@"result"][@"model"]*/];
           }
        }
        else
        {
           self.labelResult.text = [NSString stringWithFormat:@"绑定失败:[%ld]%@", error.code, error.description];
        }
    }];
}

- (void)clearResult
{
    _textFieldQRCode.text = @"";
    _labelDeviceSSID.text = @"";
    _labelResult.text = @"";
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
